package com.ray.quartz;

import com.ray.interceptor.base.AopContext;
import com.ray.interceptor.base.MetaObjectIntercept;
import com.ray.model.DataTask;
import com.ray.services.base.DbService;
import com.ray.util.Ret;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class TaskIntercept extends MetaObjectIntercept {

	@Autowired
	private Scheduler scheduler;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Ret addAfter(AopContext ac) throws Exception {
		String className = ac.record.getStr("clazz");
		String exp = ac.record.getStr("exp");

		Class clazz = Class.forName(className);
		JobDetail job = JobBuilder.newJob(clazz).withIdentity(className, className).build();
		CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(className, className).withSchedule(CronScheduleBuilder.cronSchedule(exp)).build();

		scheduler.scheduleJob(job, trigger);
		scheduler.pauseJob(job.getKey());
		
		return super.addAfter(ac);
	}

	@Override
	public Ret deleteAfter(AopContext ac) throws Exception {
		String className = ac.record.getStr("clazz");

		JobKey jobKey = JobKey.jobKey(className, className);

		scheduler.deleteJob(jobKey);
		
		return super.deleteAfter(ac);
	}

	@Override
	public Ret updateAfter(AopContext ac) throws Exception {

		String className = ac.record.getStr("clazz");
		String exp = ac.record.getStr("exp");

		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(exp);

		TriggerKey triggerKey = TriggerKey.triggerKey(className, className);
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

		scheduler.rescheduleJob(triggerKey, trigger);

		scheduler.pauseTrigger(triggerKey);
		dbService.update(base,"data_task",DataTask.dao.findById(ac.record.getInt("id")).setState(DataTask.STATE_STOP).toRecord());
		//DataTask.dao.findById(ac.record.getInt("id")).setState(DataTask.STATE_STOP).update();
		return super.updateAfter(ac);
	}
	
	@Override
	public Ret addBefore(AopContext ac) throws Exception {
		String cs = ac.record.getStr("clazz");
		DataTask task = DataTask.dao.findFirst("select * from data_task where clazz = ?", cs);
		if (task!=null) {
			throw new Exception("Job实现类已经存在:" + cs);
		}
		return super.addBefore(ac);
	}
	
}